package com.bcx.crm.plat.core.utils;

import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;

/**
 * Created by ys on 2017/11/27.
 *
 * 该类用于获取spring上下文
 */
public class SpringContextHolder implements ApplicationContextAware {
    //自动注入上下文
    private static ApplicationContext applicationContext;
    private static ServletContext servletContext;

    //根据名称获取javaBean
    public static <T> T getBean(String name){
        return (T)getApplicationContext().getBean(name);
    }
    //根据类型获取javaBean
    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }

    /**
     * spring初始化时,会通过该方法将ApplicationContext注入
     * 该类用于获取spring上下文，实现ApplicationContextAware接口的context注入函数，将其存入静态变量
     * @param applicationContext 需要注入的ApplicationContext
     * @throws BeansException 抛出bean的异常
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext=applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        checkApplicationContext();
        return applicationContext;
    }

    //该方法用于获取 spring-web中的 webApplication
    public static WebApplicationContext getWebApplicationContext(){
        return WebApplicationContextUtils.getWebApplicationContext(getBean(ServletContext.class));
    }
    //检查applicationContext
    private static void checkApplicationContext(){
        if (null==applicationContext){
            LoggerFactory.getLogger("SpringContextHolder").error("application未注入,请确保该类被注册为javabean");
            throw new IllegalStateException("SpringContextHolder");
        }
    }
    //手动获取ServletContext
    public static ServletContext getServletContext(){
        return SpringContextHolder.getWebApplicationContext().getServletContext();
    }
    public static String getClasAbsolutePath(){
        WebApplicationContext applicationContext = ContextLoader.getCurrentWebApplicationContext();
        ServletContext servletContext = applicationContext.getServletContext();
        String realPath = servletContext.getRealPath("SpringContextHolder.java");
        return realPath;
    }
}
